import moment from 'moment'

export function exportFileStream(request: (...args: any[]) => Promise<any>) {
  return request().then((response) => {
    const blob = new Blob([response.data], {
      type: 'applicationi/vnd.ms-excel'
    })
    const contentDisposition = response.headers['content-disposition']
    console.log(contentDisposition, 'contentDisposition')
    const filename = contentDisposition
      ?.split('filename=')[1]
      .split(';')[0]
      .replace(/"/g, '')

    downloadFile(
      URL.createObjectURL(blob),
      decodeURIComponent(filename || moment().format('YYYY-MM-DD') + '.xlsx')
    )
  })
}

export function downloadFile(href: string, filename?: string) {
  if (href) {
    const a: HTMLAnchorElement = document.createElement('a')
    if (filename) {
      a.download = filename
    }

    a.href = href
    a.click()
    a.target = '_blank'
    URL.revokeObjectURL(a.href)
  }
}
